<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="1100"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    :z-index="2000"
  >
    <el-button class="mb-4" type="primary" icon="Plus" @click="addSKU">添加SKU</el-button>
    <div class="mb-4">
      <vxe-table
        show-overflow="title"
        :data="form.combination_sku"
        height="280"
        :column-config="{ resizable: true }"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        :row-config="{ height: 70 }"
      >
        <vxe-column field="is_main_attribute" title="设置主SKU" width="100">
          <template #default="{ row, rowIndex }">
            <el-radio
              v-model="row.is_main_attribute"
              :label="1"
              name="1"
              size="large"
              @click.prevent="radioChange($event, rowIndex)"
              >主属性</el-radio
            >
            <el-radio
              v-model="row.is_main_attribute"
              :label="1"
              name="1"
              size="large"
              @click.prevent="radioChange($event, rowIndex)"
              >主属性</el-radio
            >
          </template>
        </vxe-column>
        <vxe-column field="attr_img" title="图片" width="60">
          <template #default="{ row }">
            <VImage :src="row.attr_img" width="52" height="52"></VImage>
          </template>
        </vxe-column>
        <vxe-column field="sku_cn_title" title="产品名称" width="150">
          <template #default="{ row }">
            <vText :value="row.sku_cn_title"></vText>
          </template>
        </vxe-column>
        <vxe-column field="spu" title="SPU">
          <template #default="{ row }">
            <vText :value="row.spu"></vText>
          </template>
        </vxe-column>
        <vxe-column field="sku" title="SKU/自定义" width="120">
          <template #default="{ row }">
            <vText :value="row.sku"></vText>
            <vText :value="row.custom_sku"></vText>
          </template>
        </vxe-column>
        <vxe-column field="specification" title="规格">
          <template #default="{ row }">
            <template v-if="row.specification">
              <div v-for="(item, index) in row.specification" :key="index">
                {{ item.name }}
              </div>
            </template>
            <template v-else>--</template>
          </template>
        </vxe-column>
        <vxe-column field="sku_product_type_text" title="产品类型"></vxe-column>
        <vxe-column field="supplier_quotation" title="供应商报价" width="200">
          <template #default="{ row }">
            <div class="flex">
              采购未税报价:
              <dataAuthority
                auth="unit_price"
                :value="row.supplier_quotation"
                :currency="row.currency"
              ></dataAuthority>
            </div>
            <div class="flex">
              采购未税价:
              <dataAuthority
                auth="purchase_untaxed_price"
                :value="row.purchase_untaxed_price"
                :currency="row.currency"
              ></dataAuthority>
            </div>
            <div class="flex">
              采购含税价:
              <dataAuthority
                auth="unit_price_tax"
                :value="row.unit_price_tax"
                :currency="row.currency"
              ></dataAuthority>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="quantity" title="数量">
          <template #default="{ row }">
            <vxe-input
              v-model="row.quantity"
              placeholder="请输入"
              @blur="blurQuantity"
            ></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="operation" title="操作" width="80">
          <template #default="{ row, rowIndex }">
            <el-link type="danger" @click="deleteRow(rowIndex)">删除</el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane label="基础信息" :name="0">
        <div class="pt-4 pb-4 pl-2 pr-2">
          <el-form
            ref="formRef"
            label-align="right"
            label-width="100"
            size="default"
            label-position="top"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="组合产品自定义SKU" props="sku" required>
                  <el-input
                    v-model="form.sku"
                    placeholder="组合产品自定义SKU"
                    oninput="value=value.replace(/[\u4e00-\u9fa5]/g, '')"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="组合类型">
                  <template #label>
                    <div class="flex items-center">
                      组合类型
                      <el-tooltip placement="top">
                        <template #content>
                          <h3>组合类型说明</h3>
                          <h3>1、销售组合：</h3>
                          <p>
                            1.1由运营发起，运营将两个及多个产品组合后刊登售卖；子SKU支持单独售卖；
                          </p>
                          <p>
                            1.2PR单以子sku进行备货；PO采购单拆分为子sku采购；头程备库单以子sku出库；客户订单以子sku发货
                          </p>
                          <p>
                            1.3虚拟组合sku，实际是子sku发货，不组合打包，直接按子SKU发货；
                          </p>
                          <h3>2、开发组合：</h3>
                          <p>
                            2.1由开发发起，开发开品时以子SKU开发后再组合售卖；子SKU支持单独售卖（通常不会单独售卖）；
                          </p>
                          <p>
                            2.2PR以组合sku备货；PO采购单拆成子sku采购；头程备库单以组合sku出库；客户订单以组合sku发货；
                          </p>
                          <p>2.3国内仓组合好打包发货；</p>
                          <h3>3、拆包组合：</h3>
                          <p>
                            3.1由开发发起，开发开品的大件产品，基于产品的尺寸特殊性，只能拆包发货（但必须完整一套发货）；
                          </p>
                          <p>3.2子SKU不支持单独售卖；且不支持绑定其他组合；</p>
                          <p>
                            3.3PR单以子sku进行备货；PO采购单拆分为子sku采购；头程备库单以子sku出库；客户订单以子sku发货
                          </p>
                          <p>
                            3.4虚拟组合sku，实际是子sku发货，不组合打包，直接按子SKU发货；
                          </p>
                          <p>
                            3.5拆包组合SKU，若需要退税，则需确认供应商是否可以基于子SKU开票，若不行，则不可定义为拆包组合；
                          </p>
                        </template>
                        <svg-icon icon-class="QuestionFilled"></svg-icon>
                      </el-tooltip>
                    </div>
                  </template>

                  <el-select class="w-full" v-model="form.combined_sources" disabled>
                    <el-option
                      v-for="item in combinationTypeOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="组合产品中文名称" props="sku_cn_title" required>
                  <el-input
                    v-model="form.sku_cn_title"
                    placeholder="组合产品中文名称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="组合产品英文名称" props="sku_en_title" required>
                  <el-input
                    v-model="form.sku_en_title"
                    placeholder="组合产品英文名称"
                    oninput="value=value.replace(/[\u4e00-\u9fa5]/g, '')"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品尺寸">
                  <VGroup>
                    <el-input
                      v-model="form.product_size_cm.length"
                      oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                      :controls="false"
                      placeholder="长"
                    />
                    <el-input
                      v-model="form.product_size_cm.width"
                      oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                      :controls="false"
                      placeholder="宽"
                    />
                    <el-input
                      v-model="form.product_size_cm.height"
                      oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                      :controls="false"
                      placeholder="高"
                    >
                    </el-input>
                    <span class="append">cm</span>
                  </VGroup>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品毛重" required>
                  <el-input
                    class="w-ful1l"
                    v-model="form.gross_weight_g"
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                    placeholder="产品毛重"
                  >
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品净重" required>
                  <el-input
                    class="w-ful1l"
                    v-model="form.net_weight_g"
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                    placeholder="产品净重"
                  >
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品包装尺寸/cm">
                  <VGroup>
                    <el-input
                      v-model="form.packing_size_cm.length"
                      placeholder="长"
                      oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                    ></el-input>
                    <el-input
                      v-model="form.packing_size_cm.width"
                      placeholder="宽"
                      oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                    ></el-input>
                    <el-input
                      v-model="form.packing_size_cm.height"
                      placeholder="高"
                      oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
                    >
                    </el-input>
                    <span class="append">cm</span>
                  </VGroup>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品物流属性" required>
                  <select-logistics
                    class="w-full"
                    v-model="form.logistics_attributes"
                    placeholder="请选择产品物流属性"
                    @change="changeLogistics"
                  ></select-logistics>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="组合产品包装清单">
                  <el-input
                    type="textarea"
                    v-model="form.package_description"
                    placeholder="组合产品包装清单"
                    :autosize="{ minRows: 4, maxRows: 8 }"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="flex">
            <div>
              <el-icon>
                <div>
                  <el-icon>
                    <Warning />
                  </el-icon>
                </div>
              </el-icon>
            </div>
            <div>
              <div class="text-gray-400 text-xs">
                1、组合SKU自定义SKU：根据主属性SKU的产品分类简称进行生成，支持修改；
              </div>
              <div class="text-gray-400 text-xs">
                2、组合产品中文中文名称/英文名称默认生成规则：根据所选子SKU的自定义SKU与组成数量进行拼接展示；支持修改；
                <br />例如：PCARVP01454_ASSHOI×1+PCAWCF00234_ASSHOK×1
              </div>
              <div class="text-gray-400 text-xs">
                3、生成的组合SKU资料，默认复制主属性子SKU的信息，可后续编辑修改。
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="供应商信息" :name="1">
        <SupplierInfo ref="SupplierInfoRef" v-model="supplier" type="combination">
          <template #handle>
            <el-dropdown
              :max-height="290"
              trigger="click"
              placement="bottom-start"
              @command="handleSelectSupplier($event, 'supplier')"
            >
              <el-button :disabled="!form.combination_sku.length">
                获取子SKU供应商
                <i
                  style="font-size: 10px !important"
                  class="dk-iconfont icon-ArrowDown"
                />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="(item, index) in skuSupplierOptions"
                    :key="index"
                    :command="item.id"
                    >{{ item.full_name }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </SupplierInfo>
      </el-tab-pane>

      <el-tab-pane label="报关信息" :name="2">
        <CustomsInfo v-model="supplier.goods_sku_customs" type="combination">
          <template #handle>
            <el-dropdown
              :max-height="290"
              trigger="click"
              placement="bottom-start"
              @command="handleSelectSupplier($event, 'customs')"
            >
              <el-button :disabled="!form.combination_sku.length">
                获取子SKU报关信息
                <i
                  style="font-size: 10px !important"
                  class="dk-iconfont icon-ArrowDown"
                />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="(item, index) in skuSupplierOptions"
                    :key="index"
                    :command="item.id"
                    >{{ item.full_name }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </CustomsInfo>
      </el-tab-pane>
      <el-tab-pane label="欧英代产品信息" :name="3">
        <TradeAgent
          v-model="supplier.goods_sku_trade_agent"
          type="combination"
        ></TradeAgent>
      </el-tab-pane>
      <el-tab-pane label="产品加工说明" :name="4">
        <IdentificationProcessing
          v-model="supplier.goods_sku_identification_processing"
        ></IdentificationProcessing>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <selectCombinationSKU
    ref="addSKURef"
    @assign="assignRecords"
    :checkedList="form.combination_sku"
  >
  </selectCombinationSKU>
</template>
<script setup name="AddCombinationSKU" lang="jsx">
import { onMounted, reactive, toRefs, computed, watch } from "vue";
import selectCombinationSKU from "@/components/selectCombinationSKU";
import VImage from "@/components/Image/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { uploadImg } from "@/api/index.js";
import { createCombinationSku, getSKUCombinationRelation } from "../../api/index";
import CustomsInfo from "@/components/Supplier/CustomsInfo.vue";
import IdentificationProcessing from "@/components/Supplier/IdentificationProcessing.vue";
import TradeAgent from "@/components/Supplier/TradeAgent.vue";
import SupplierInfo from "@/components/Supplier/SupplierInfo.vue";
import { getskuSupplierAll, getSupplierList } from "@/api/index.js";
import { fieldPermission } from "@/utils/permission.js";
import { removeIds, deepClone } from "@/utils/index.js";
import SelectLogistics from "@/components/SelectLogistics";
import { submit_validate_supplier, submit_validate_customs } from "@/utils/validate.js";
const combinationTypeOptions = [
  {
    label: "开发组合",
    value: 1,
  },
  {
    label: "销售组合",
    value: 2,
  },
  {
    label: "拆包组合",
    value: 3,
  },
];

const titleMap = new Map([
  [1, "新增开发组合SKU"],
  [2, "新增销售组合SKU"],
  [3, "新增拆包组合SKU"],
]);

const emits = defineEmits(["query"]);

const data = reactive({
  visible: false,
  loading: false,
  form: {
    combination_sku: [],
    combined_sources: 0, // 0 无组合来源 1 产品组合 2 销售组合
  },
  load: false,
  activeName: 0,
  supplier: null,
  skuSupplierOptions: [],
  title: "",
});

const {
  visible,
  loading,
  form,
  load,
  activeName,
  supplier,
  skuSupplierOptions,
  title,
} = toRefs(data);

// 初始化
const getForm = () => {
  return {
    sku: "",
    sku_cn_title: "",
    sku_en_title: "",
    package_description: "",
    sku: "",
    sku_cn_title: "",
    sku_en_title: "",
    package_description: "",
    combination_sku: [],
    sku_id: null,
    packing_size_cm: { length: "", width: "", height: "" },
    product_size_cm: { length: "", width: "", height: "" },
  };
};

const open = async (type) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  form.value.combined_sources = type;
  title.value = titleMap.get(type);
  visible.value = true;
  init();
};

// 开发组合，则默认‘sz2k（加工）’ 销售组合、拆包组合，则默认‘SZ2K’
const supplier_code_map = new Map([
  [1, "4640"], // 开发组合
  [2, "16137"], // 销售组合
  [3, "16137"], // 拆包组合
]);

const SupplierInfoRef = ref();
const init = async () => {
  try {
    const supplier_code = supplier_code_map.get(form.value.combined_sources);
    const res = await getSupplierList({
      supplier_code,
    });
    if (res.data.length == 0) return ElMessage.error(`${supplier_code}供应商不存在`);
    const find = res.data.find((i) => i.supplier_code === supplier_code);
    if (find) {
      SupplierInfoRef.value.selectSupplier(find);
    }
  } catch (e) {
    console.error(e);
  }
};

const close = () => {
  // nextTick(() => {
  //   const container = document.querySelector("#scrollContainer");
  //   container.scrollTo({
  //     top: 0,
  //     behavior: "smooth",
  //   });
  // });

  initForm();
  activeName.value = 0;
  visible.value = false;
};

const addSKURef = ref();
const addSKU = () => {
  nextTick(() => {
    addSKURef.value.open(1);
  });
};
// 赋值
const assignRecords = (val) => {
  const records = val.map((i, index) => {
    i = {
      id: i.id,
      combination_sku_id: i.id,
      spu: i.spu,
      sku_id: i.id,
      sku: i.sku,
      attr_img: i.attr_img,
      custom_sku: i.custom_sku,
      sku_cn_title: i.sku_cn_title,
      sku_en_title: i.sku_en_title,
      is_main_attribute: i.is_main_attribute || 0,
      quantity: i.quantity || 1,
      purchase_price: i.purchase_price,
      gross_weight_g: i.gross_weight_g,
      net_weight_g: i.net_weight_g,
      packing_weight_g: i.packing_weight_g,
      packing_size_cm: i.packing_size_cm,
      product_size_cm: i.product_size_cm,
      specification: i.specification,
      sku_product_type_text: i.sku_product_type_text,
      unit_price_tax: i.unit_price_tax,
      purchase_untaxed_price: i.purchase_untaxed_price,
      supplier_quotation: i.supplier_quotation,
      logistics_attributes: Number(i.logistics_attributes),
      logistics_attributes_name: i.logistics_attributes_name,
    };
    if (form.value.combination_sku.length == 0 && index == 0) {
      i.is_main_attribute = 1;
      form.value.sku_id = i.sku_id;
    }
    return i;
  });
  form.value.combination_sku.push(...records);
  computedSKU();
  getskuSupplierOptions();
};

const computedSKU = (type = "select") => {
  if (form.value.combination_sku.length > 0) {
    const findIndex = form.value.combination_sku.findIndex(
      (i) => i.is_main_attribute == 1
    );
    let data = form.value.combination_sku[findIndex];
    let number = Math.floor(Math.random() * 90) + 10;
    form.value.sku = `${data.custom_sku}_zh${number}`;
    if (type == "select") {
      form.value.sku_cn_title = form.value.sku_cn_title || data.sku_cn_title;
      form.value.sku_en_title = form.value.sku_en_title || data.sku_en_title;
      form.value.logistics_attributes =
        form.value.logistics_attributes || data.logistics_attributes;
      form.value.logistics_attributes_name =
        form.value.logistics_attributes_name || data.logistics_attributes_name;
    }
    const total = form.value.combination_sku.reduce((acc, cur) => {
      return acc + Number(cur.supplier_quotation) * Number(cur.quantity || 0);
    }, 0);
    supplier.value.unit_price = total;
    nextTick(() => {
      SupplierInfoRef.value.blurcalculate("unit_price");
    });
  } else {
    form.value.sku_cn_title = "";
    form.value.sku_en_title = "";
    form.value.sku = "";
  }
  computedWeight();
};

const computedWeight = () => {
  if (
    !Array.isArray(form.value.combination_sku) ||
    form.value.combination_sku.length === 0
  ) {
    form.value.gross_weight_g = "";
    form.value.net_weight_g = "";
    form.value.packing_size_cm = { length: "", width: "", height: "" };
    form.value.product_size_cm = { length: "", width: "", height: "" };
    return;
  }

  const calculateWeights = (skuItems) => {
    return skuItems.reduce(
      (acc, cur) => {
        if (cur.hasOwnProperty("gross_weight_g") && cur.hasOwnProperty("net_weight_g")) {
          acc.gross_weight_g +=
            Number(cur.gross_weight_g || 0) * Number(cur.quantity || 0);
          acc.net_weight_g += Number(cur.net_weight_g || 0) * Number(cur.quantity || 0);
        }
        return acc;
      },
      { gross_weight_g: 0, net_weight_g: 0 }
    );
  };

  const calculateDimensions = (skuItems, key) => {
    let maxWidth = 0;
    let maxHeight = 0;
    let totalVolume = 0;

    skuItems.forEach((cur) => {
      const width = Number(cur[key].width || 0) * Number(cur.quantity || 0);
      const height = Number(cur[key].height || 0);
      const volume =
        Number(cur[key].width || 0) *
        Number(cur[key].height || 0) *
        Number(cur[key].length || 0) *
        Number(cur.quantity || 0);

      maxWidth = Math.max(maxWidth, width);
      // maxHeight = Math.max(maxHeight, height);
      maxHeight += height;
      totalVolume += volume;
    });

    let length = 0;
    if (maxWidth !== 0 || maxHeight !== 0) {
      length = totalVolume / (maxWidth * maxHeight);
    }

    return {
      width: maxWidth.toFixed(2),
      height: maxHeight.toFixed(2),
      length: length.toFixed(2),
    };
  };

  const weights = calculateWeights(form.value.combination_sku);
  const packing_size_cm_dimensions = calculateDimensions(
    form.value.combination_sku,
    "packing_size_cm"
  );
  const product_size_cm_dimensions = calculateDimensions(
    form.value.combination_sku,
    "product_size_cm"
  );

  form.value.gross_weight_g = weights.gross_weight_g;
  form.value.net_weight_g = weights.net_weight_g;
  form.value.packing_size_cm = packing_size_cm_dimensions;
  form.value.product_size_cm = product_size_cm_dimensions;
};

const radioChange = (val, rowIndex) => {
  form.value.combination_sku = form.value.combination_sku.map((item, index) => {
    if (index == rowIndex) {
      item.is_main_attribute = 1;
      form.value.sku_id = item.sku_id;
      item.is_main_attribute = 1;
      form.value.sku_id = item.sku_id;
    } else {
      item.is_main_attribute = 0;
      item.is_main_attribute = 0;
    }
    return item;
  });
  computedSKU();
};

const deleteRow = (index) => {
  form.value.combination_sku.splice(index, 1);
  computedSKU();
  getskuSupplierOptions();
};

let formTips = new Map([
  ["sku", "请填写主SKU"],
  ["sku_cn_title", "请填写中文标题"],
  ["sku_en_title", "请填写英文标题"],
  // ["package_description", "请填写包装清单"],
  ["combination_sku", "请添加SKU"],
  ["sku_id", "请添加SKU"],
  ["gross_weight_g", "请填写毛重"],
  ["net_weight_g", "请填写净重"],
]);

const save = async () => {
  let keys = Object.keys(form.value);
  let key_values = Object.values(form.value);
  if (key_values.some((i) => !i || i.length == 0)) {
    let index = key_values.findIndex((i) => !i);
    let key = keys[index];
    let tips = formTips.get(key);

    if (tips) {
      ElMessage.error(tips);
      return false;
    }
  }

  const massageArray = [];
  form.value.combination_sku.length &&
    form.value.combination_sku.forEach((element, index) => {
      if (!element.quantity) {
        massageArray.push(`请输入第 ${index + 1} 列数量`);
      } else if (element.quantity == 0) {
        massageArray.push(`第 ${index + 1} 列数量必须大于1`);
      }
    });

  if (massageArray && massageArray.length) {
    ElMessageBox({
      title: "提示",
      message: () => <div>{massageArray.map((d) => h("p", null, d))}</div>,
    });
    return;
  }
  let totalNumber =
    form.value.combination_sku.length &&
    form.value.combination_sku.reduce((pre, cur) => {
      return pre + Number(cur.quantity || 0);
    }, 0);

  if (totalNumber < 2) {
    ElMessage.error("商品数量小于2，禁止创建组合SKU！");
    return;
  }

  if (!form.value.gross_weight_g) {
    ElMessage.error("毛重必须大于0");
    return;
  }

  if (!form.value.net_weight_g) {
    ElMessage.error("净重必须大于0");
    return;
  }

  if (Number(form.value.gross_weight_g) < Number(form.value.net_weight_g)) {
    ElMessage.error("毛重需要>=净重");
    return;
  }

  if (!form.value.logistics_attributes) {
    ElMessage.error("请选择产品物流属性");
    return;
  }

  const supplierData = Object.assign({}, supplier.value);

  // 1）销售组合、拆包组合，仅必须绑定供应商和维护价格，其他不判断必填 2）开发组合：需和正常SKU一样判断必填
  if (form.value.combined_sources == 1) {
    // 校验
    const is_submit_validate_supplier = await submit_validate_supplier(supplier.value);
    const is_submit_validate_customs = await submit_validate_customs(
      supplier.value.goods_sku_customs,
      supplier.value
    );

    if (!is_submit_validate_supplier && !is_submit_validate_customs) {
      return;
    }

    let declare_elements = "";
    supplierData.goods_sku_customs.declare_elements_list.forEach((item, index) => {
      const value = item.value;
      declare_elements += value;
      if (index < supplierData.goods_sku_customs.declare_elements_list.length - 1) {
        declare_elements += "|";
      }
      item.sort = index;
      return item;
    });
    supplierData.goods_sku_customs.declare_elements = declare_elements;
  } else {
    const is_submit_validate_supplier = await submit_validate_supplier(supplier.value);
    if (!is_submit_validate_supplier) {
      return;
    }

    const is_flag = checkCustoms(supplier.value.goods_sku_customs);

    if (!is_flag) {
      supplierData.goods_sku_customs = {};
    } else {
      const is_submit_validate_customs = await submit_validate_customs(
        supplier.value.goods_sku_customs,
        supplier.value
      );
      if (!is_submit_validate_customs) {
        return;
      }
      let declare_elements = "";
      supplierData.goods_sku_customs.declare_elements_list.forEach((item, index) => {
        const value = item.value;
        declare_elements += value;
        if (index < supplierData.goods_sku_customs.declare_elements_list.length - 1) {
          declare_elements += "|";
        }
        item.sort = index;
        return item;
      });
      supplierData.goods_sku_customs.declare_elements = declare_elements;
    }
  }

  try {
    const sku_ids = form.value.combination_sku.map((i) => i.sku_id);
    const skus = form.value.combination_sku.map((i) => i.sku);

    const res = await getSKUCombinationRelation({
      sku_ids,
    });
    if (res.data.length) {
      const massageArray = res.data;
      await new Promise((resolve) => {
        ElMessageBox({
          title: "提示",
          customStyle: { maxWidth: "600px" },
          showCancelButton: true,
          message: (
            <div>
              {massageArray.map((d, index) =>
                h(
                  "p",
                  null,
                  `${index + 1}、子SKU：`,
                  d.combination
                    .map((k) => {
                      if (skus.some((i) => i == k.sku)) {
                        return h(
                          "span",
                          {
                            style: {
                              backgroundColor: "#faad14",
                            },
                          },
                          `${k.sku}`
                        );
                      } else {
                        return h("span", null, `${k.sku}`);
                      }
                    })
                    .map((span, idx, array) => {
                      return [span, h("span", null, `*${d.combination[idx].quantity}; `)];
                    })
                    .flat(),
                  `，已生成组合SKU：${d.sku || d.custom_sku} `,
                  h(
                    "span",
                    { style: { color: "#3487ff" } },
                    `（${d.combination[0].combined_sources_text})`
                  )
                )
              )}
              {h(
                "p",
                { style: "font-weight: bold; margin-top:6px" },
                `是否继续生成组合SKU? 点击确认执行`
              )}
            </div>
          ),
        }).then((res) => {
          if (res == "confirm") {
            resolve();
          }
        });
      });
    }
  } catch (e) {
    throw Error(e);
  }

  const attr_img = await generateMainImage();

  try {
    const formData = {
      ...form.value,
      goods_sku_supplier: [
        {
          ...supplierData,
        },
      ],
      attr_img,
    };
    const res = await createCombinationSku({ ...formData });
    ElMessage.success(res.message);
    close();
    setTimeout(() => {
      emits("query");
    }, 1000);
  } catch (e) {
    throw Error(e);
  }
};

const checkCustoms = (customs) => {
  // 输入校验：确保 customs 是一个对象
  if (!customs || typeof customs !== "object" || Array.isArray(customs)) {
    return false;
  }

  // 检查 customs 是否为空对象
  if (Object.keys(customs).length === 0) {
    return false;
  }

  // 解构
  const {
    goods_sku_customs_info = [],
    declare_elements_list = [],
    ...otherProps
  } = customs;

  // 检查 goods_sku_customs_info 中每个元素的 country_id 是否存在
  if (
    Object.values(otherProps).every((value) => !value) &&
    goods_sku_customs_info.every((item) => !item.country_id) &&
    declare_elements_list.every((item) => !(item.text || item.value))
  ) {
    return false;
  }

  return true;
};

const initForm = () => {
  form.value = getForm();
  supplier.value = {
    is_default_supplier: 1,
    goods_sku_customs: {
      goods_sku_customs_info: [
        {
          customs_currency: "USD",
        },
      ],
      declare_elements_list: [{}],
    },
    goods_sku_trade_agent: {},
    goods_sku_identification_processing: [],
  };
};

onMounted(() => {
  initForm();
});
defineExpose({ open });

// 数量输入框失去焦点
const blurQuantity = (val) => {
  if (val) {
    computedSKU("number");
  }
};

const generateMainImage = async () => {
  const images = form.value.combination_sku
    .map((row) => row.attr_img)
    .filter((url) => url);

  if (images.length === 0) return;

  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  const targetSize = 1200; // 目标尺寸 1200x1200
  const imageSize = 600; // 每张子图片的尺寸 600x600

  if (images.length != 1 && images.length <= 4) {
    const imagePromises = images.map((url) => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = "anonymous"; // 添加这一行
        img.src = url;
        img.onload = () => {
          resolve(img);
        };
        img.onerror = reject;
      });
    });

    const loadedImages = await Promise.all(imagePromises);

    canvas.width = targetSize;
    canvas.height = targetSize;

    let currentX = 0;
    let currentY = 0;

    // 计算水平居中的起始位置
    if (images.length === 2) {
      currentY = imageSize / 2;
    }

    loadedImages.forEach((img, index) => {
      const quantity = form.value.combination_sku[index].quantity;

      // 缩放图片
      ctx.drawImage(img, currentX, currentY, imageSize, imageSize);

      // 显示组成量
      ctx.font = "bold 60px Arial";
      ctx.fillStyle = "#8001FF";
      ctx.shadowColor = "#D2946D"; // 阴影颜色
      ctx.shadowOffsetX = 4; // 水平偏移量
      ctx.shadowOffsetY = 4; // 垂直偏移量
      ctx.shadowBlur = 4; // 阴影模糊程度

      const textX = currentX + 20;

      ctx.fillText(`${quantity}PCS`, textX, currentY + imageSize - 10);

      // 更新下一个图片的位置
      currentX += imageSize;
      if (currentX >= targetSize) {
        currentX = 0;
        currentY += imageSize;
      }
    });
  } else {
    return form.value.combination_sku[0].attr_img;
  }

  const main_image_url = await downloadBase64(canvas.toDataURL());
  return main_image_url;
};

const downloadBase64 = async (dataUrl, fileName = "download") => {
  const parts = dataUrl.split(";base64,");
  const contentType = parts[0].split(":")[1];
  let strArr = contentType.split("/");
  const raw = window.atob(parts[1]);
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  const blob = new Blob([uInt8Array], { type: contentType });
  const newFilename = fileName + "." + strArr[1];
  const file = new File([blob], newFilename, { type: contentType });
  let formData = new FormData();
  formData.append("file", file);
  try {
    const { data } = await uploadImg(formData);
    // 调用 el-form 内部的校验方法（可自动校验）
    return data["data-show-file"];
  } catch (error) {
    throw Error(error);
  }
};

const getskuSupplierOptions = async () => {
  try {
    const sku_ids = form.value.combination_sku.map((i) => i.sku_id);
    const res = await getskuSupplierAll({ sku_ids });
    const list = [];
    res.data.forEach((i) => {
      let supplier = i.goods_sku_supplier.map((j) => {
        j.sku = i.sku;
        const supplier_name_code = fieldPermission(
          "supplier_name",
          j.supplier_name,
          j.supplier_code
        );
        j.full_name = `${supplier_name_code} (${j.sku})`;
        return j;
      });
      list.push(...supplier);
    });
    skuSupplierOptions.value = list;
    computeAdditionalFields();
  } catch (e) {
    console.error(e);
  }
};

const computeAdditionalFields = () => {
  // 是否退税
  const is_refund_tax = skuSupplierOptions.value.some((sku) => sku.is_refund_tax == 2);

  if (is_refund_tax) {
    supplier.value.is_refund_tax = 2;
    supplier.value.invoice_tax_rate = 13;
    const taxPoints = skuSupplierOptions.value.map((sku) => sku.tax_rate);
    const uniqueTaxPoints = [...new Set(taxPoints)];
    if (uniqueTaxPoints.length === 1) {
      supplier.value.tax_rate = uniqueTaxPoints[0];
    } else {
      const hasTaxRefund = skuSupplierOptions.value.some((sku) => sku.is_tax_refund);
      supplier.value.tax_rate = hasTaxRefund ? 13 : Math.max(...taxPoints);
    }
  } else {
    supplier.value.is_refund_tax = 3;
    supplier.value.tax_rate = 0;
    supplier.value.invoice_tax_rate = 0;
  }

  // 计算生产天数、运输天数、入库天数 采购天数
  supplier.value.production_days = Math.max(
    ...skuSupplierOptions.value.map((sku) => sku.production_days)
  );
  supplier.value.purchase_transportation_days = Math.max(
    ...skuSupplierOptions.value.map((sku) => sku.purchase_transportation_days)
  );
  supplier.value.inventory_days = Math.max(
    ...skuSupplierOptions.value.map((sku) => sku.inventory_days)
  );
  supplier.value.purchase_days =
    supplier.value.production_days +
    supplier.value.purchase_transportation_days +
    supplier.value.inventory_days;
  nextTick(() => {
    SupplierInfoRef.value.blurcalculate("unit_price");
  });
};
const handleSelectSupplier = (val, type) => {
  let find = skuSupplierOptions.value.find((i) => i.id == val);
  if (!find) return ElMessage.error(`未找到供应商信息`);
  if (type == "supplier") {
    const filterSupplier = removeIds(deepClone(find));
    const purchase_untaxed_price = supplier.value.purchase_untaxed_price;
    const unit_price_tax = supplier.value.unit_price_tax;
    const unit_price = supplier.value.unit_price;

    if (!filterSupplier.goods_sku_trade_agent) {
      filterSupplier.goods_sku_trade_agent = {};
    }

    if (!filterSupplier.goods_sku_customs) {
      filterSupplier.goods_sku_customs = {
        goods_sku_customs_info: [
          {
            customs_currency: "USD",
          },
        ],
      };
    }

    supplier.value = {
      ...filterSupplier,
      purchase_untaxed_price,
      unit_price_tax,
      unit_price,
    };
    nextTick(() => {
      SupplierInfoRef.value.blurcalculate("unit_price");
    });
  } else if (type == "customs") {
    supplier.value.goods_sku_customs = removeIds(deepClone(find.goods_sku_customs));
  }

  if (!supplier.value.goods_sku_customs.goods_sku_customs_info?.length) {
    supplier.value.goods_sku_customs.goods_sku_customs_info = [
      {
        customs_currency: "USD",
      },
    ];
  }

  if (!supplier.value.goods_sku_customs.declare_elements_list?.length) {
    supplier.value.goods_sku_customs.declare_elements_list = [{}];
  }
};

const changeLogistics = (val) => {
  form.value.logistics_attributes_name = val;
};

const options = reactive(inject("options"));
</script>
<style lang="scss">
.message-box-custom {
  width: 600px !important;
}
.append {
  color: #909399;
  background: #f5f7fa;
  padding: 0 20px;
  border: 1px solid #e5e7eb;
  width: 110px;
}
</style>
